package com.ominext.utils;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

public class ImageUtils {
	public static Bitmap rotate(String picturePath)
	{
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
		
		ExifInterface ei;
		try {
			ei = new ExifInterface(picturePath);
			int orientation = ei.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
			case ExifInterface.ORIENTATION_UNDEFINED:
				if (DeviceUtils.isLGDevice()) {
					bitmap = ImageUtils.rotateByDegree(bitmap, 90);	
				}
				
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				bitmap = ImageUtils.rotateByDegree(bitmap, 180);
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				bitmap = ImageUtils.rotateByDegree(bitmap, 270);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return bitmap;
	}
	
	public static Bitmap rotateByDegree(Bitmap b, int degrees) {
		if (degrees != 0 && b != null) {
			Matrix m = new Matrix();

			m.setRotate(degrees, (float) b.getWidth() / 2,
					(float) b.getHeight() / 2);
			try {
				Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
						b.getHeight(), m, true);
				if (b != b2) {
					b.recycle();
					b = b2;
				}
			} catch (OutOfMemoryError ex) {
				throw ex;
			}
		}
		return b;
	}

	// method resize image
	public static Bitmap resizeBitmap(Bitmap image, int newHeight, int newWidth) {
		// get with and height of image
		int height = image.getHeight();
		int width = image.getWidth();

		// get scale
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();

		// resize image by with or height
		if (scaleWidth > scaleHeight)
			scaleWidth = scaleHeight;
		matrix.postScale(scaleWidth, scaleWidth);

		Bitmap resizedBitmap = Bitmap.createBitmap(image, 0, 0, width, height,
				matrix, false);
		return resizedBitmap;
	}

}
